package com.ss.summer.sql.core;

import com.ss.summer.core.exceptions.SummerCustomSqlException;
import com.ss.summer.entity.SummerInstance;
import com.ss.summer.sql.annotations.SApplyId;
import com.ss.summer.sql.annotations.SField;
import com.ss.summer.sql.annotations.SNotField;
import com.ss.summer.sql.annotations.STable;
import com.ss.summer.sql.model.SummerApply;
import lombok.Data;

import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 生成sql
 * @author xia17
 * @date 2019/8/1 10:36
 */
@Data
public class CustomSql {
    private List<String> params = new ArrayList<>();
    private String tableName;
    private String applyId;
    /**
     * k为对象属性名 ，v为 sql查询字段属性名
     */
    private Map<String,String> paramMap = new HashMap<>();
    /**
     * 查询的参数  apply.id as APPLY_id
     */
    private String fi;
    /**
     * 连接条件  tableName as apply on ins.apply_id = apply.id
     */
    private String join;

    public CustomSql(Class clz){
        super();
        this.init(clz);
    }

    private void init(Class clz){
        //判断类注解获取表名
        if (!clz.isAnnotationPresent(STable.class)){
            throw new SummerCustomSqlException(clz.getName()+"未使用@STable注解标记数据库表名");
        }
        STable summerTable = (STable)clz.getAnnotation(STable.class);
        boolean needCast =  summerTable.cast();
        if ("".equals(summerTable.value())){
            this.tableName = this.cast(clz.getSimpleName());
        }else {
            this.tableName = summerTable.value();
        }
        //判空
        //获取连接条件，申请id
        Field[] fields = clz.getDeclaredFields();
        for (int i = 0;i<fields.length;i++){
            Field field = fields[i];
            //获取@SApplyId注解，
            if (field.isAnnotationPresent(SApplyId.class)){
                SApplyId sApplyId = field.getAnnotation(SApplyId.class);
                if ("".equals(sApplyId.value())){
                    this.applyId = this.cast(field.getName());
                }else {
                    this.applyId = sApplyId.value();
                }
                this.params.add(this.applyId);
                //添加***
                this.paramMap.put(field.getName(),this.applyId);
                break;
            }
            //未标级 则抛出异常
            if (i == fields.length-1){
                throw new SummerCustomSqlException(clz.getName()+"未使用@SApplyId注解标记申请id");
            }
        }
        //判空
        //获取查询的数据
        for (Field field : fields) {
            //静态变量不为参数
            if (Modifier.isStatic(field.getModifiers())){
                continue;
            }
            //标了@SNotField 不为参数
            if (field.isAnnotationPresent(SNotField.class)){
                continue;
            }
            //主键Id 已经添加进去
            if (field.isAnnotationPresent(SApplyId.class)){
                continue;
            }
            //标了SField 使用value值 为字段名
            if (field.isAnnotationPresent(SField.class)){
                SField sField = field.getAnnotation(SField.class);
                if ("".equals(sField.value())){
                    throw new SummerCustomSqlException("@SField注解的value不能为空串");
                }
                this.params.add(sField.value());
                //添加***
                this.paramMap.put(field.getName(),sField.value());
            }else {
                //默认使用自动转换下划线
                if (needCast){
                    this.params.add(this.cast(field.getName()));
                    this.paramMap.put(field.getName(),this.cast(field.getName()));
                }else {
                    //使用原生类 字段名
                    this.params.add(field.getName());
                    this.paramMap.put(field.getName(),field.getName());
                }
            }
        }
        //生成sql
        createSql();
    }

    /**
     * 驼峰转下划线
     * @param s
     * @return
     */
    private String cast(String s){
        StringBuilder sb = new StringBuilder();
        for (int i=0;i<s.length();i++){
            char c = s.charAt(i);
            if (c>64 && c<91){
                char d = (char) (c+32);
                if (i == 0){
                    sb.append(d);
                }else {
                    sb.append('_');
                    sb.append(d);
                }
            }else {
                sb.append(c);
            }
        }
        return sb.toString();
    }

    /**
     * 生成sql
     */
    private void createSql(){
        //表连接
        this.join = this.tableName + " as apply on ins.apply_id = apply." + this.applyId + "   ";
        //查询数据
        StringBuilder sb = new StringBuilder();
        for (String param : this.paramMap.keySet()) {
            sb.append(" ,apply.");
            sb.append(param);
            sb.append(" as apply");
            sb.append(param);
            sb.append('\n');
        }
        this.fi = sb.toString();
    }

    /**
     * 获取返回结果中的key
     * @param fieldName
     * @return
     */
    private String getResultKey(String fieldName){
        return this.paramMap.get(fieldName);
    }

    /**
     * 获取替换参数Map
     * @return
     */
    public Map<String,Object> toTemplateParamMap(){
        Map<String, Object> map = new HashMap<>(8);
        map.put("fi",this.getFi());
        map.put("join",this.getJoin());
        return map;
    }

    public<T extends SummerApply> List<T> toEntityList(List<Map<String,Object>> maps, Class<T> clz){
        ArrayList<T> list = new ArrayList<>();
        try {
            for (Map<String, Object> result : maps) {
                T t = clz.newInstance();
                Field[] fields = t.getClass().getDeclaredFields();
                for (Field field : fields) {
                    field.setAccessible(true);
                    field.set(t,result.get("apply" + this.getResultKey(field.getName())));
                }
                t.setSummerInstance(new SummerInstance(result));
                list.add(t);
            }
        }catch (IllegalAccessException | InstantiationException e){
            e.printStackTrace();
            throw new SummerCustomSqlException("查询异常");
        }
        return list;
    }



}
